const $redis = require("../lib/redis") // 你的redis配置文件路径
module.exports = function (Data) {
    Data.tagsWithScoreToObj=function(tags=[]){
        // ////console.log("tagsWithScoreToObj:",tags)
        let newTags = []
        for (let i=0;i<tags.length;i++) {
            if(!(i%2)){
                newTags.push({
                    name:tags[i],
                    score:tags[i+1]
                })
            }
        }
        return newTags;
    },
    // 热门tags
    Data.getHotTags= async function (limit=5) {
        let tags = await $redis.zrevrange("tags:topic:count",0, limit,"WITHSCORES");
        if(!tags){
            tags = [];
        }
		return Data.tagsWithScoreToObj(tags);
	};
    // 用户关注的tags
    Data.getUserFollowTags= async function (uid,limit=10) {
        if(!uid){
            return [];
        }
        let tags = await $redis.zrevrange("user:"+uid+":subscription_tag",0, limit,"WITHSCORES");
        if(!tags){
            tags = [];
        }
        // ////console.log("user_read_tag:"+uid,tags)
        return Data.tagsWithScoreToObj(tags);
	};
    // 获取首页上的标签 
    Data.getUserIndexTags= async function (uid,limit=10) {
        let tags1 =await  Data.getHotTags(5);
        let tags2 = await  Data.getUserFollowTags(uid,limit);
        let tags =  tags2.concat(tags1)
        let tal_score=0;
        // 去重
        let tmp=[];
        let output_tags=[];
        for (const key in tags) {
            if(tmp.indexOf(tags[key].name)==-1){
                tmp.push(tags[key].name);
                output_tags.push(tags[key]);
                tal_score=tal_score+Number(tags[key].score);
            }  
        }
        for (const key in output_tags) {
            output_tags[key].score = output_tags[key].score/tal_score*1.5
        }
        return output_tags;
	};

    // 订阅标签
    Data.subscribeTag= async function (uid=0,tags=[]) {
        let args=["user:"+uid+":subscription_tag"];
        let score =0
        for (const key in tags) {
            if (tags[key]) {
            let tag = tags[key];
            score = await $redis.zscore("user:"+uid+":subscription_tag",tag)
            score =score>0? Number(score)+1 : 1
            args.push(score)
            args.push(tag)
            }
        }
        // ////console.log("args:",args)
        const foo = await $redis.zadd(...args)
        return foo;
    }

}